import {
	login
} from '@/api/user'

const getDefaultState = () => {
	return {
		name: '',
		student_id:'',
		token: '',
		id_card: '',
		class_name: '',
		major_name: ''
	}
}

const state = getDefaultState()
const mutations = {
	SET_NAME: (state, name) => {
		state.name = name
	},
	SET_ID: (state, id) => {
		state.student_id = id
	},
	SET_TOKEN: (state, token) => {
		state.token = token
	},
	SET_ID_CARD: (state, id_card) => {
		state.id_card = id_card
	},
	SET_CLASS: (state, class_name) => {
		state.class_name = class_name
	},
	SET_MAJOR: (state, major) => {
		state.major_name = major
	}
}
const actions = {
	// 用户登录
	login({commit}, userInfo) {
		const {id_card,password} = userInfo
		return new Promise((resolve, reject) => {
			login({
				id_card: id_card,
				password: password
			}).then(response => {
				const {data,headers} = response
				uni.setStorageSync('userInfo', JSON.stringify(data.data))
				uni.setStorageSync('token', headers.token)
				commit('SET_NAME', data.data.username)
				commit('SET_TOKEN', headers.token)
				commit('SET_CLASS', data.data.class_name)
				commit('SET_ID_CARD',id_card)
				commit('SET_CLASS', data.data.class_name)
				commit('SET_MAJOR', data.data.major_name)
				commit('SET_ID', data.data.key)
				response.data.data.id_card=id_card
				uni.setStorageSync('userInfo',response.data.data)
				resolve()
			}).catch(error => {
				reject(error)
			})
		})
	},
	getInfo({commit}) {
		return new Promise((resolve, reject)=>{
			const token=uni.getStorageSync('token')
			const userInfo=uni.getStorageSync('userInfo')
			if(token == '' ||userInfo == ''){
				this.$toast('考试已结束')
				reject()
			}
			resolve({token,userInfo})
		})
	},

	// 用户登出
	logout({commit,state}) {
		uni.clearStorage()
		return new Promise((resolve, reject) => {
			commit('SET_NAME', null)
			commit('SET_TOKEN',null)
			commit('SET_CLASS',null)
			commit('SET_MAJOR', null)
			commit('SET_ID_CARD',null)
			commit('SET_ID', null)
			resolve()
		})
	},

}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}
